const router = require('koa-router')()
var multer = require('multer')
var fs = require('fs');
var path = require('path');

//查询全部攻略
router.get('/getmethod', async (ctx, next) => {
    let sql = "select * from method order by id DESC";
    let result = await ctx.db.EXCUTE(sql);
    ctx.body = { data: result, status: "获取攻略信息成功" }
})
//搜索某个攻略
router.post('/search', async (ctx, next) => {
    let title = ctx.request.body.title;
    let sql = `select * from method where title like'%${title}%' order by id DESC`;
    let result = await ctx.db.EXCUTE(sql, [title]);
    if (result.length == 0) {
        ctx.body = { code: 400, status: "输入信息错误,无数据", data: [] }
    } else {
        ctx.body = { code: 200, status: "搜索信息成功", data: result }
    }
})
//添加攻略
//上传图片
const upload = multer({ dest: 'public/methodimg' })
upload.single("file")
router.post('/submethod', async (ctx, next) => {
    let res = ctx.request.body
    let file = res.image;
    let imgurl = '';
    if (file != '') {
        let basePath = './public/methodimg/';
        let filename = Date.now() + '.png'
        let filePath = basePath + filename;
        // 存到文件夹
        console.log(filePath)
        const base64 = file.replace(/^data:image\/\w+;base64,/, "")
        const dataBuffer = Buffer.from(base64, 'base64')
        fs.writeFile(filePath, dataBuffer, function (err) {//用fs写入文件
            if (err) {
                console.log(err);
            } else {
                console.log("成功")
            }
        })
        imgurl = '../trip-koa/public/methodimg' + "/" + filename;
    }

    let sqlCount = 'select max(distinct id) as count from method;';
    let num = await ctx.db.EXCUTE(sqlCount)
    let count = num[0].count;
    let id = count + 1;
    let place = id;
    let title = ctx.request.body.title;
    let content = ctx.request.body.content;
    let image = imgurl;
    let sql = 'insert into method(id,place,title,content,image) values(?,?,?,?,?)'
    let args = [
        id,
        place,
        title,
        content,
        image,
    ]
    let result = await ctx.db.EXCUTE(sql, args);
    ctx.body = { "code": 200, "msg": "success", status: "添加成功", data: [] }
})

//删除攻略
router.post('/delmethod', async (ctx, next) => {
    let id = ctx.request.body.id;
    //先查询保存本地存储的图片地址
    let selsql = `select image from method where id=${id}`;
    let selresult = await ctx.db.EXCUTE(selsql, [id]);
    let fileimg = selresult[0].image;
    //删除数据库
    let delsql = 'delete from method where id=?';
    let result = await ctx.db.EXCUTE(delsql, [id]);
    //删除对应的本地图片
    if (fileimg != '') {
        fileimg = fileimg.split("/")[4];
        let name = fileimg;
        let baseFilePath = './public/methodimg/';
        var files = [];
        if (fs.existsSync(baseFilePath)) {
            files = fs.readdirSync(baseFilePath);
            files.forEach(function (item) {
                var curPath = path.join(baseFilePath, fileimg);
                console.log(curPath)
                if (fs.statSync(curPath).isDirectory()) {//是否是目录
                    deleteFile(curPath);//递归删除目录
                } else {
                    if (item.indexOf(name) > -1) {
                        fs.unlinkSync(curPath); 18
                        console.log("删除文件：" + curPath);
                    }
                }
            });
        } else {
            console.log("给定的路径不存在！");
        }
    }
    ctx.body = { "code": 200, "msg": "ok", status: "删除成功" };
})

//修改攻略
router.post('/editmethod', async (ctx, next) => {
    let res = ctx.request.body
    let file = res.image;
    let imgurl;
    let id = ctx.request.body.id;
    if (file.split('/')[0] != '') {
        //先删除本地存储的原有图片
        let selsql = `select image from method where id=${id}`;
        let selresult = await ctx.db.EXCUTE(selsql, [id]);
        let fileimg = selresult[0].image;
        if (fileimg) {
            fileimg = fileimg.split("/")[4];
            let name = fileimg;
            let baseFilePath = './public/methodimg/';
            var files = [];
            if (fs.existsSync(baseFilePath)) {
                files = fs.readdirSync(baseFilePath);
                files.forEach(function (item) {
                    var curPath = path.join(baseFilePath, fileimg);
                    console.log(curPath)
                    if (fs.statSync(curPath).isDirectory()) {//是否是目录
                        deleteFile(curPath);//递归删除目录
                    } else {
                        if (item.indexOf(name) > -1) {
                            fs.unlinkSync(curPath); 18
                            console.log("删除文件：" + curPath);
                        }
                    }
                });
            } else {
                console.log("给定的路径不存在！");
            }
        }


        //添加新的图片
        let basePath = './public/methodimg/';
        let filename = Date.now() + '.png'
        let filePath = basePath + filename;
        // 存到文件夹
        console.log(filePath)
        const base64 = file.replace(/^data:image\/\w+;base64,/, "")
        const dataBuffer = Buffer.from(base64, 'base64')
        fs.writeFile(filePath, dataBuffer, function (err) {//用fs写入文件
            if (err) {
                console.log(err);
            } else {
                console.log("成功")
            }
        })
        imgurl = '../trip-koa/public/methodimg' + "/" + filename
    } else {
        file = file.split("/")[2];
        file = [file.split('.')[0], file.split('.')[2]];
        file = file.join('.')
        console.log(file)
        imgurl = '../trip-koa/public/methodimg' + "/" + file;
    }

    let title = ctx.request.body.title;
    let content = ctx.request.body.content;
    let image = imgurl;
    let sql = 'update method set title=?,content=?,image=? where id=?'
    let args = [
        title,
        content,
        image,
        id,
    ]
    let result = await ctx.db.EXCUTE(sql, args);
    ctx.body = { "code": 200, "status": "修改成功" };
})

//上传图片
router.post('/upload', async (ctx, next) => {
    console.log(ctx.request.body)
})

module.exports = router